package myTeam.timeShop.shiro.realm;

import java.util.List;

import myTeam.timeShop.bean.TbUser;
import myTeam.timeShop.service.UserService;
import myTeam.timeShop.util.MyMD5Util;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.ByteSource;


public class UserRealm implements Realm{
	UserService userService;
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	
	@Override
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		// TODO 自动生成的方法存根
		String account = token.getPrincipal().toString();
		//这里的密码是经过编码过后的,所以要转码
		String password =new String((char[])token.getCredentials());
		//密码转码
		//根据转码后的密码进行校验
		List<TbUser> list = userService.findByAccountAndPassword(account, MyMD5Util.toMD5String(password));
		if(list.size()==0){
			throw new IncorrectCredentialsException();
		}else{
			//把用户id 代替为身份
			return new SimpleAuthenticationInfo(list.get(0).getUserId(), password, getName());
		}
	}

	@Override
	public String getName() {
		// TODO 自动生成的方法存根
		return "userReaml";
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		// TODO 自动生成的方法存根
		return token instanceof UsernamePasswordToken;
	}

	



}
